import 'dart:async';

import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:xmshop/app/routes/app_pages.dart';
import 'package:xmshop/app/services/screenAdapter.dart';

import '../controllers/product_content_controller.dart';
import './first_page_view.dart';
import './second_page_view.dart';
import './third_page_view.dart';
import './cart_item_num_view.dart';

class ProductContentView extends GetView<ProductContentController> {
  const ProductContentView({super.key});

  //showBottomAttr,action筛选在哪点击
  void showBottomAttr(int action) {
    Get.bottomSheet(
      GetBuilder<ProductContentController>(
        init: controller,
        builder: (controller) {
          return Container(
            color: Colors.white,
            padding: EdgeInsets.all(ScreenAdapter.width(20)),
            width: double.infinity,
            height: ScreenAdapter.height(1200),
            child: Stack(
              children: [
                ListView(
                  children: [
                    ...controller.pcontent.value.attr!.map((v) {
                      return Wrap(
                        children: [
                          Container(
                            padding: EdgeInsets.only(
                              top: ScreenAdapter.height(20),
                              left: ScreenAdapter.width(20),
                            ),
                            width: ScreenAdapter.width(1040),
                            child: Text(
                              "${v.cate}",
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(
                              top: ScreenAdapter.height(20),
                              left: ScreenAdapter.width(20),
                            ),
                            width: ScreenAdapter.width(1040),
                            child: Wrap(
                              children: v.attrList!.map((value) {
                                return InkWell(
                                  onTap: () {
                                    print(value["title"]);
                                    controller.changeAttr(
                                      v.cate,
                                      value["title"],
                                    );
                                  },
                                  child: Container(
                                    margin: EdgeInsets.all(
                                      ScreenAdapter.width(20),
                                    ),
                                    child: Chip(
                                      padding: EdgeInsets.only(
                                        left: ScreenAdapter.width(20),
                                        right: ScreenAdapter.width(20),
                                      ),
                                      backgroundColor: value["checked"] == true
                                          ? Colors.red
                                          : const Color.fromARGB(
                                              31,
                                              223,
                                              213,
                                              213,
                                            ),
                                      label: Text(value["title"]),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                        ],
                      );
                    }),
                    Padding(
                      padding: EdgeInsets.all(ScreenAdapter.height(20)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text(
                            "数量",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          CartItemNumView(),
                        ],
                      ),
                    ),
                  ],
                ),
                Positioned(
                  right: 2,
                  top: 0,
                  child: IconButton(
                    onPressed: () {
                      Get.back();
                    },
                    icon: Icon(Icons.close, color: Colors.black45),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Expanded(
                    flex: 1,
                    child: action == 1
                        ? Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: ScreenAdapter.height(120),
                                  margin: EdgeInsets.only(
                                    right: ScreenAdapter.width(20),
                                  ),
                                  child: ElevatedButton(
                                    onPressed: () {
                                      controller.addCart();
                                    },
                                    style: ButtonStyle(
                                      shape: WidgetStateProperty.all(
                                        RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(
                                            5,
                                          ), // 圆角半径（单位：像素）
                                        ),
                                      ),
                                      backgroundColor: WidgetStateProperty.all(
                                        const Color.fromRGBO(255, 165, 0, 0.9),
                                      ),
                                      foregroundColor: WidgetStateProperty.all(
                                        Colors.white,
                                      ),
                                    ),
                                    child: const Text("加入购物车"),
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: ScreenAdapter.height(120),
                                  margin: EdgeInsets.only(
                                    right: ScreenAdapter.width(20),
                                  ),
                                  child: ElevatedButton(
                                    onPressed: () {
                                      controller.buy();
                                    },
                                    style: ButtonStyle(
                                      shape: WidgetStateProperty.all(
                                        RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(
                                            5,
                                          ), // 圆角半径（单位：像素）
                                        ),
                                      ),
                                      backgroundColor: WidgetStateProperty.all(
                                        const Color.fromRGBO(253, 1, 0, 0.9),
                                      ),
                                      foregroundColor: WidgetStateProperty.all(
                                        Colors.white,
                                      ),
                                    ),
                                    child: const Text("立即购买"),
                                  ),
                                ),
                              ),
                            ],
                          )
                        : Container(
                            height: ScreenAdapter.height(120),
                            margin: EdgeInsets.only(
                              right: ScreenAdapter.width(20),
                            ),
                            child: ElevatedButton(
                              onPressed: () {
                                if (action == 2) {
                                  controller.addCart();
                                } else if (action == 3) {
                                  controller.buy();
                                }
                              },
                              style: ButtonStyle(
                                shape: WidgetStateProperty.all(
                                  RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(
                                      5,
                                    ), // 圆角半径（单位：像素）
                                  ),
                                ),
                                backgroundColor: WidgetStateProperty.all(
                                  const Color.fromRGBO(253, 1, 0, 0.9),
                                ),
                                foregroundColor: WidgetStateProperty.all(
                                  Colors.white,
                                ),
                              ),
                              child: const Text("确定"),
                            ),
                          ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _appBar(BuildContext context) {
    return Obx(
      () => AppBar(
        title: SizedBox(
          width: ScreenAdapter.width(400),
          height: ScreenAdapter.height(96),
          child: controller.showTabs.value
              ? Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: controller.tabsList.map((value) {
                    return InkWell(
                      onTap: () {
                        controller.changeSelectIndex(value["id"]);
                        if (value["id"] == 1) {
                          Scrollable.ensureVisible(
                            controller.gk1.currentContext as BuildContext,
                            duration: const Duration(milliseconds: 500),
                          );
                        } else if (value["id"] == 2) {
                          Scrollable.ensureVisible(
                            controller.gk2.currentContext as BuildContext,
                            duration: const Duration(milliseconds: 500),
                          );
                          Timer.periodic(Duration(milliseconds: 501), (timer) {
                            controller.scrollController.jumpTo(
                              controller.scrollController.position.pixels -
                                  ScreenAdapter.height(120),
                            );
                            timer.cancel();
                          });
                        } else if (value["id"] == 3) {
                          Scrollable.ensureVisible(
                            controller.gk3.currentContext as BuildContext,
                            duration: const Duration(milliseconds: 500),
                          );
                          Timer.periodic(Duration(milliseconds: 501), (timer) {
                            controller.scrollController.jumpTo(
                              controller.scrollController.position.pixels -
                                  ScreenAdapter.height(120),
                            );
                            timer.cancel();
                          });
                        }
                      },
                      child: Padding(
                        padding: EdgeInsets.all(0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              value["title"],
                              style: TextStyle(
                                fontSize: ScreenAdapter.fontSize(36),
                              ),
                            ),
                            controller.selectTabsIndex.value == value["id"]
                                ? Container(
                                    margin: EdgeInsets.only(
                                      top: ScreenAdapter.height(10),
                                    ),
                                    width: ScreenAdapter.width(60),
                                    height: ScreenAdapter.height(2),
                                    color: Colors.red,
                                  )
                                : Container(
                                    margin: EdgeInsets.only(
                                      top: ScreenAdapter.height(10),
                                    ),
                                    width: ScreenAdapter.width(60),
                                    height: ScreenAdapter.height(2),
                                  ),
                          ],
                        ),
                      ),
                    );
                  }).toList(),
                )
              : const Text(""),
        ),
        centerTitle: true,
        //配置AppBar透明效果
        backgroundColor: Colors.white.withValues(
          alpha: controller.opcity.value,
        ), //实现透明导航
        elevation: 0, //实现透明导航
        //内容滚动时阴影高度
        scrolledUnderElevation: 0,
        leading: Container(
          alignment: Alignment.center,
          child: SizedBox(
            width: ScreenAdapter.width(70),
            height: ScreenAdapter.width(70),
            child: ElevatedButton(
              onPressed: () {
                Get.back();
              },
              style: ButtonStyle(
                padding: WidgetStateProperty.all(EdgeInsets.all(0)),
                alignment: Alignment.center,
                backgroundColor: WidgetStateProperty.all(Colors.black12),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                shape: WidgetStateProperty.all(const CircleBorder()),
              ),
              child: const Icon(Icons.arrow_back),
            ),
          ),
        ),
        actions: [
          Container(
            margin: EdgeInsets.only(right: ScreenAdapter.width(30)),
            width: ScreenAdapter.width(70),
            height: ScreenAdapter.width(70),
            child: ElevatedButton(
              onPressed: () {},
              style: ButtonStyle(
                padding: WidgetStateProperty.all(EdgeInsets.all(0)),
                alignment: Alignment.center,
                backgroundColor: WidgetStateProperty.all(Colors.black12),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                shape: WidgetStateProperty.all(const CircleBorder()),
              ),
              child: const Icon(Icons.file_upload_outlined),
            ),
          ),
          Container(
            margin: EdgeInsets.only(right: ScreenAdapter.width(30)),
            width: ScreenAdapter.width(70),
            height: ScreenAdapter.width(70),
            child: ElevatedButton(
              onPressed: () {
                showMenu(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  color: Colors.black12.withValues(alpha: 0.4),
                  context: context,
                  position: RelativeRect.fromLTRB(
                    ScreenAdapter.width(750),
                    ScreenAdapter.height(190),
                    ScreenAdapter.width(30),
                    0,
                  ),
                  items: [
                    PopupMenuItem(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.home, color: Colors.white),
                          Text("首页", style: TextStyle(color: Colors.white)),
                        ],
                      ),
                    ),
                    PopupMenuItem(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.message, color: Colors.white),
                          Text("消息", style: TextStyle(color: Colors.white)),
                        ],
                      ),
                    ),
                    PopupMenuItem(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.star, color: Colors.white),
                          Text("收藏", style: TextStyle(color: Colors.white)),
                        ],
                      ),
                    ),
                  ],
                );
              },
              style: ButtonStyle(
                padding: WidgetStateProperty.all(EdgeInsets.all(0)),
                alignment: Alignment.center,
                backgroundColor: WidgetStateProperty.all(Colors.black12),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                shape: WidgetStateProperty.all(const CircleBorder()),
              ),
              child: const Icon(Icons.more_horiz_rounded),
            ),
          ),
        ],
      ),
    );
  }

  Widget _body() {
    return SingleChildScrollView(
      controller: controller.scrollController,
      child: Column(
        children: [
          FirstPageView(showBottomAttr),
          SecondPageView(subHeader),
          ThirdPageView(),
        ],
      ),
    );
  }

  Widget _bottom() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        height: ScreenAdapter.height(160),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            top: BorderSide(
              width: ScreenAdapter.width(2),
              color: Colors.black12,
            ),
          ),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(5),
            topRight: Radius.circular(5),
          ),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: ScreenAdapter.width(200),
              height: ScreenAdapter.height(160),
              child: InkWell(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    InkWell(
                      onTap: () {
                        Get.toNamed(Routes.Cart);
                      },
                      child: Icon(Icons.shopping_cart),
                    ),
                    Text("购物车"),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                height: ScreenAdapter.height(120),
                margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
                child: ElevatedButton(
                  onPressed: () {
                    showBottomAttr(2);
                  },
                  style: ButtonStyle(
                    shape: WidgetStateProperty.all(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5), // 圆角半径（单位：像素）
                      ),
                    ),
                    backgroundColor: WidgetStateProperty.all(
                      const Color.fromRGBO(255, 165, 0, 0.9),
                    ),
                    foregroundColor: WidgetStateProperty.all(Colors.white),
                  ),
                  child: const Text("加入购物车"),
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                height: ScreenAdapter.height(120),
                margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
                child: ElevatedButton(
                  onPressed: () {
                    showBottomAttr(3);
                  },
                  style: ButtonStyle(
                    shape: WidgetStateProperty.all(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5), // 圆角半径（单位：像素）
                      ),
                    ),
                    backgroundColor: WidgetStateProperty.all(
                      const Color.fromRGBO(253, 1, 0, 0.9),
                    ),
                    foregroundColor: WidgetStateProperty.all(Colors.white),
                  ),
                  child: const Text("立即购买"),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget subHeader() {
    return Container(
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: controller.subTabsList.map((value) {
          return Expanded(
            child: InkWell(
              onTap: () {
                controller.changeSelectedSubTabsIndex(value["id"]);
              },
              child: Container(
                height: ScreenAdapter.height(120),
                alignment: Alignment.center,
                child: Text(
                  value["title"],
                  style: TextStyle(
                    color: value["id"] == controller.selectedSubTabsIndex.value
                        ? Colors.red
                        : Colors.black87,
                  ),
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //两种实现顶部透明的方式，另一种是首页自定义AppBar
      extendBodyBehindAppBar: true,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(ScreenAdapter.height(120)),
        child: _appBar(context),
      ),
      body: Stack(
        children: [
          _body(),
          _bottom(),
          Obx(
            () => controller.showSubHeaderTabs.value
                ? Positioned(
                    left: 0,
                    top:
                        ScreenAdapter.getStatusBarHeight() +
                        ScreenAdapter.height(120),
                    right: 0,
                    child: subHeader(),
                  )
                : const Text(""),
          ),
        ],
      ),
    );
  }
}
